using System;
using System.Collections.Generic;

public class UDPPacket 
{    
    public const int maxSendContentLengthOneTime = 1376;

    public static int maxSendTotalOneTime =>
        maxSendContentLengthOneTime + s_headBytesCount + s_indexBytesCount + s_TailBytesCount;

    public const string Tail = "&&&&";
    
    public static int s_headBytesCount => 4; 
    public static int s_indexBytesCount => 4; 

    public static int s_TailBytesCount => 4;

    private Dictionary<int, byte[]> m_Data;
    public byte[] data
    {
        get
        {
            if (!m_ReceiveEnd)
            {
                GameDebug.LogError("has not receive end");
                return null;
            }
            
            List<byte>_data = new List<byte>();
            foreach (var bytese in m_Data)
            {
                _data.AddRange(bytese.Value);
            }
            return _data.ToArray();
        }
    }

    private int m_Id;
    public int id => m_Id;

    private const int NotEndIndex = -1;
    private int m_EndIndex = NotEndIndex;
    public int endIndex => m_EndIndex;
    
    protected bool m_ReceiveEnd;
    public bool receiveEnd => m_ReceiveEnd;

    public UDPPacket(int id)
    {
        m_Data = new Dictionary<int, byte[]>();
        m_Id = id;
    }
    
    
    public void OnReceivePacket(byte[] data)
    {
        int id = BitConverter.ToInt32(data,0);

        if (m_Id != id)
        {
            GameDebug.LogError($"m_Id:{m_Id} != receive data id:{id}");
        }

        int index = BitConverter.ToInt32(data, 4);

        int headTotalCount = s_headBytesCount + s_indexBytesCount;
        
        //GameDebug.Log($" id：{id} 序号：{index}");
      
        byte[] tail = new byte[s_TailBytesCount];
        Array.Copy(data,data.Length - tail.Length, tail, 0,tail.Length);
        string tailTsr = System.Text.Encoding.UTF8.GetString(tail);

        if (tailTsr.Equals(Tail))
        {
            //GameDebug.Log($"收到尾包：{index}");
            m_EndIndex = index;
        }
        
        byte[] contentData = new byte[data.Length - headTotalCount - s_TailBytesCount];

        Array.Copy(data, headTotalCount, contentData, 0, contentData.Length);
        
        m_Data[index] = contentData;


        CheckReceiveEnd();
    }

    void CheckReceiveEnd()
    {
        if (m_EndIndex == NotEndIndex)
        {
            return;
        }

        bool end = true;
        for (int i = 0; i <= m_EndIndex; i++)
        {
            if (!m_Data.ContainsKey(i))
                end = false;
        }

        m_ReceiveEnd = end;

        #if UNITY_EDITOR
        if (end)
        {
            GameDebug.Log($"接收完成  m_EndIndex：{m_EndIndex}  {data.Length}");
        }
        else
        {
            GameDebug.Log($"接收到 m_EndIndex:{m_EndIndex}   data：{m_Data.GetDictStr()}");
        }
        #endif
    }

}